package com.chukun.tx.service.impl;

import com.chukun.tx.dto.OrderDto;
import com.chukun.tx.exception.OrderCreateException;
import com.chukun.tx.mapper.MqMessageMapper;
import com.chukun.tx.mapper.OrderMapper;
import com.chukun.tx.message.queue.DefaultMessageProcessor;
import com.chukun.tx.message.queue.MessageProcessor;
import com.chukun.tx.model.MqMessage;
import com.chukun.tx.model.Order;
import com.chukun.tx.service.IOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author chukun
 * 订单处理逻辑
 */
@Service("orderService")
public class OrderService implements IOrderService {


    private static final Logger LOGGER = LoggerFactory.getLogger(OrderService.class);

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private MqMessageMapper messageMapper;


    @Override
    @Transactional(value = "orderTransactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Order createOrder(OrderDto orderDto) throws OrderCreateException {
        Order order = null;
        try {
            order = new Order();
            order.oderDto2Do(orderDto);
            // 生成订单号
            order.setOrderNo(System.nanoTime() + "");
            orderMapper.insertOrder(order);
            // 创建消息
            MqMessage message = new MqMessage();
            message.order2MqMessage(order);
            messageMapper.insertMessage(message);
            MessageProcessor defaultProcessor = DefaultMessageProcessor.getDefaultProcessor();
            defaultProcessor.putMsg(message);
        } catch (Exception e) {
            LOGGER.error("OrderService createOrder error ", e);
            throw new OrderCreateException("OrderService createOrder error: " + e.getMessage(), e);
        }
        return order;
    }
}
